package stu.sup.controller.buycar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import stu.sup.dto.BuycarDto;
import stu.sup.entity.Buycart;
import stu.sup.entity.Product;
import stu.sup.entity.UserLogin;
import stu.sup.service.IBuycarService;
import stu.sup.service.IProductService;
import stu.sup.service.IUserLoginService;
import stu.sup.util.JsonResult;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class BuyCarController {
    @Autowired
    private IBuycarService buycarService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IUserLoginService userLoginService;

    //添加商品到购物车
    @RequestMapping("/Buycar")
    @ResponseBody
    public String buycarController(Model model, HttpServletRequest request){
        String id=request.getParameter("productId");
        Object name=request.getSession().getAttribute("loginUserName");
        System.out.println(name);
        UserLogin userLogin=userLoginService.selectbyUsername(name.toString());
        System.out.println(userLogin);
        Product product=productService.selectbyId(Integer.parseInt(id));
        System.out.println(product);
        Buycart buycart=buycarService.updateBuycar(product,userLogin);
        boolean flag=false;
        System.out.println(buycart);
        if (null!=buycart){
            System.out.println("添加成功");
            flag=true;
            model.addAttribute("flag",flag);
            return "view/product";
        }
        else {
            System.out.println("添加失败");
            model.addAttribute("flag",flag);
            return "view/product";
        }
    }

    //展示购物车
    @RequestMapping("/show/buycar")
    public String buycarshow(Model model,HttpServletRequest request){
        Object name=request.getSession().getAttribute("loginUserName");
        UserLogin userLogin=userLoginService.selectbyUsername(name.toString());
        List<BuycarDto> buycarDtos=buycarService.findByuser(1,1,userLogin.getId());
        model.addAttribute("buycar",buycarDtos);
        return "view/buycar";
    }
    //删除购物车
    @RequestMapping("/delate/buycar")
    public String delatebuycar(Model model,HttpServletRequest request, Integer value){
        System.out.println(value);
        Buycart buycart=new Buycart();
        buycart.setBuycartId(value);
        buycarService.delatebuycar(buycart);
        return "view/buycar";
    }
}
